﻿Imports System.Data.OleDb
Imports System.Data.SqlClient
Imports ESRI.ArcGIS.Carto
Imports System.IO
Imports ESRI.ArcGIS.SystemUI
Imports ESRI.ArcGIS.Controls
Imports ESRI.ArcGIS.Display
Imports ESRI.ArcGIS.Geometry
Imports ESRI.ArcGIS.Geodatabase
Imports System.Xml
Imports ESRI.ArcGIS.esriSystem

Public Class Workspace
    Public removed As Boolean = False
    Private m_mapControl As IMapControl3 = Nothing
    Public m_mapDocumentName As String = Nothing
    Public workspaceName As String = Nothing
    Public dbConnexion As String = Nothing
    Public paramsHandler As newWS
    Public layersMap As Dictionary(Of String, LayerMapping) = New Dictionary(Of String, LayerMapping)
    Public selectedLayer As ILayer = Nothing
    Public layerWhereDraw As ILayer = Nothing
    Public xmlPath As String = Nothing
    Public configPath As String = Nothing
    Private lastGeometry As IElement = Nothing
    Public databaseName As String
    Public firstLayerLoaded As Boolean = False
    Public siteDAO As SiteDAO = New SiteDAO()
    Dim configLayers As List(Of LayersSiteConfig) = Nothing
    Public oidParentText As TextBox
    ' 1 = creation, 2 = chargement
    Public mode As Integer = 1



    

    Private Sub Workspace_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        m_mapControl = CType(axMapControl1.Object, IMapControl3)
        AxEditorToolbar.AddItem("esriControls.ControlsEditingEditorMenu", 0, -1, False, 0, esriCommandStyles.esriCommandStyleIconOnly)
        AxEditorToolbar.AddItem("esriControls.ControlsEditingEditTool", 0, -1, False, 0, esriCommandStyles.esriCommandStyleIconOnly)
        AxEditorToolbar.AddItem("esriControls.ControlsEditingSketchTool", 0, -1, False, 0, esriCommandStyles.esriCommandStyleIconOnly)
        AxEditorToolbar.AddItem("esriControls.ControlsUndoCommand", 0, -1, True, 0, esriCommandStyles.esriCommandStyleIconOnly)
        AxEditorToolbar.AddItem("esriControls.ControlsRedoCommand", 0, -1, False, 0, esriCommandStyles.esriCommandStyleIconOnly)
        AxEditorToolbar.AddItem("esriControls.ControlsEditingTaskToolControl", 0, -1, True, 0, esriCommandStyles.esriCommandStyleIconOnly)
        AxEditorToolbar.AddItem("esriControls.ControlsEditingTargetToolControl", 0, -1, True, 0, esriCommandStyles.esriCommandStyleIconOnly)

        AxTOCControl1.LayerVisibilityEdit = esriTOCControlEdit.esriTOCControlAutomatic

        If mode = 1 Then 'creation
            createNewWs()
            saveWorkspace()
        ElseIf mode = 2 Then 'chargement
            loadWS()
        Else
            Close()
            Exit Sub
        End If

        getLayersConfig()
    End Sub
    Public Sub showGeolocation(ByVal textBox As TextBox)
        oidParentText = textBox
        oidValue.Text = String.Empty
        MainTab.SelectedIndex = 0
        mapGeomContainer.Panel1Collapsed = False
    End Sub
    Public Sub getLayersConfig()
        configLayers = siteDAO.getSiteDefaultLayers()
    End Sub
    Private Sub loadWS()
        If configPath IsNot Nothing Then
            Dim XmlDoc As XmlDocument = New XmlDocument()
            XmlDoc.Load(configPath)
            workspaceName = XmlDoc.GetElementsByTagName("Workspace").Item(0).Attributes().GetNamedItem("Name").InnerText
            databaseName = XmlDoc.GetElementsByTagName("Workspace").Item(0).Attributes().GetNamedItem("Code").InnerText
            'Me.Text = workspaceName
            Dim mxdFilePathList As XmlNodeList = XmlDoc.DocumentElement.GetElementsByTagName("mxdFile")
            Dim configPathList As XmlNodeList = XmlDoc.DocumentElement.GetElementsByTagName("configFile")

            m_mapDocumentName = mxdFilePathList.ItemOf(0).InnerText
            xmlPath = configPathList.ItemOf(0).InnerText

            Dim xmlDocConfig As New XmlDocument()
            xmlDocConfig.Load(xmlPath)

            'Try
            '    firstLayerLoaded = Convert.ToBoolean(xmlDocConfig.DocumentElement.GetElementsByTagName("Configuration").Item(0).Attributes().GetNamedItem("FirstLayerLoaded").InnerText)
            '    If Not firstLayerLoaded Then
            '        addLayerToMap("COMMUNES", axMapControl1.ActiveView.FocusMap, m_mapDocumentName)
            '        firstLayerLoaded = True
            '    End If
            'Catch ex As Exception

            'End Try

            dbConnexion = xmlDocConfig.DocumentElement.GetElementsByTagName("Database").Item(0).InnerText
            Dim arrTemp As String() = dbConnexion.Split(";"c)
            dbConnexionStr.Text = "        Connecté à la base de donnée : " & arrTemp(0).Split("="c)(1) & "\" & arrTemp(1).Split("="c)(1)

            m_mapControl.LoadMxFile(m_mapDocumentName)
            m_mapControl.DocumentMap = workspaceName
            m_mapControl.Map.Name = workspaceName


            'Dim listMappings As XmlNodeList = xmlDocConfig.DocumentElement.GetElementsByTagName("Mapping")

            'For Each mapping As XmlNode In listMappings
            '    Dim layerMapp As LayerMapping = New LayerMapping()
            '    layerMapp.layerName = mapping.Attributes().GetNamedItem("couche").InnerText
            '    layerMapp.layerTable = mapping.Attributes().GetNamedItem("table").InnerText
            '    layerMapp.layerForm = mapping.Attributes().GetNamedItem("formulaire").InnerText
            '    layersMap.Add(layerMapp.layerName, layerMapp)
            '    'layersMap.Add(mapping.Attributes().GetNamedItem("couche").InnerText, mapping.Attributes().GetNamedItem("table").InnerText)
            'Next
        End If
    End Sub
    Private Sub createNewWs()
        dbConnexion = paramsHandler.dbConnexionStr
        workspaceName = paramsHandler.workspaceName
        Dim codeSite As String = paramsHandler.databaseName
        dbConnexionStr.Text = "        Connecté à la base de donnée : " & paramsHandler.databaseServer & "\" & paramsHandler.databaseName
        xmlPath = getSiteXmlFilePath(codeSite) 'paramsHandler.pathToInstall & System.IO.Path.DirectorySeparatorChar & paramsHandler.workspaceName & ".xml"
        configPath = getSiteConfigFilePath(codeSite)  'paramsHandler.pathToInstall & System.IO.Path.DirectorySeparatorChar & paramsHandler.workspaceName & ".silm"

        m_mapDocumentName = getSiteMapDocumentFilePath(codeSite)  ' paramsHandler.pathToInstall & System.IO.Path.DirectorySeparatorChar & paramsHandler.workspaceName & ".mxd"

        Dim mapDocument As IMapDocument = New MapDocument()
        Dim pIMxd As IMxdContents
        mapDocument.New(m_mapDocumentName)
        pIMxd = DirectCast(m_mapControl.Map, IMxdContents)
        mapDocument.ReplaceContents(pIMxd)
        mapDocument.Save(True, True)
        mapDocument.Close()

        Dim XmlDoc As XmlDocument = New XmlDocument()
        Dim root As XmlElement = XmlDoc.CreateElement("Workspace")
        Dim wsNameAttribute As XmlAttribute = XmlDoc.CreateAttribute("Name")
        wsNameAttribute.InnerText = paramsHandler.workspaceName
        root.Attributes().Append(wsNameAttribute)

        Dim mxdNode As XmlElement = XmlDoc.CreateElement("mxdFile")
        mxdNode.InnerText = m_mapDocumentName
        root.AppendChild(mxdNode)

        Dim configNode As XmlElement = XmlDoc.CreateElement("configFile")
        configNode.InnerText = xmlPath
        root.AppendChild(configNode)

        XmlDoc.AppendChild(root)
        XmlDoc.Save(configPath)
        m_mapControl.DocumentMap = workspaceName
        m_mapControl.Map.Name = workspaceName
    End Sub


    Private Sub m_mapControl_OnMapReplaced(ByVal sender As System.Object, ByVal e As ESRI.ArcGIS.Controls.IMapControlEvents2_OnMapReplacedEvent) Handles axMapControl1.OnMapReplaced
        'get the current document name from the MapControl
        m_mapDocumentName = m_mapControl.DocumentFilename

        'if there is no MapDocument, diable the Save menu and clear the statusbar
        If m_mapDocumentName = String.Empty Then
            menuSaveDoc.Enabled = False
            statusXY.Text = String.Empty
        Else
            'enable the Save menu and write the doc name to the statusbar
            menuSaveDoc.Enabled = True
            statusXY.Text = System.IO.Path.GetFileName(m_mapDocumentName)
        End If
    End Sub

    Private Sub m_mapControl_OnMouseMove(ByVal sender As System.Object, ByVal e As ESRI.ArcGIS.Controls.IMapControlEvents2_OnMouseMoveEvent) Handles axMapControl1.OnMouseMove
        statusXY.Text = String.Format("{0}, {1}  {2}", e.mapX.ToString("#######.##"), e.mapY.ToString("#######.##"), m_mapControl.MapUnits.ToString().Substring(4))
    End Sub

    Public Sub saveLayers()
        If m_mapControl.CheckMxFile(m_mapDocumentName) Then
            'create a new instance of a MapDocument
            Dim mapDoc As IMapDocument = New MapDocument()
            mapDoc.Open(m_mapDocumentName, String.Empty)

            'Make sure that the MapDocument is not readonly
            If mapDoc.IsReadOnly(m_mapDocumentName) Then
                MsgBox("Le document est en lecture seule!")
                mapDoc.Close()
                Return
            End If

            'Replace its contents with the current map
            mapDoc.ReplaceContents(CType(m_mapControl.Map, IMxdContents))

            'save the MapDocument in order to persist it
            mapDoc.Save(mapDoc.UsesRelativePaths, False)

            'close the MapDocument
            mapDoc.Close()
        End If
    End Sub

    Public Sub saveXML()
        Dim XmlDoc As XmlDocument = New XmlDocument()
        Dim root As XmlElement = XmlDoc.CreateElement("Configuration")

        Dim loadAttr As XmlAttribute = XmlDoc.CreateAttribute("FirstLayerLoaded")
        loadAttr.InnerText = firstLayerLoaded.ToString()
        root.Attributes.Append(loadAttr)
        Dim databaseNode As XmlElement = XmlDoc.CreateElement("Database")
        databaseNode.InnerText = dbConnexion
        root.AppendChild(databaseNode)

        Dim LayersNode As XmlElement = XmlDoc.CreateElement("Mappings")
        For Each layerData As String In layersMap.Keys()
            Dim layerMapp As LayerMapping = layersMap.Item(layerData)
            Dim confCoucheNode As XmlElement = XmlDoc.CreateElement("Mapping")

            Dim coucheAttribute As XmlAttribute = XmlDoc.CreateAttribute("couche")
            coucheAttribute.InnerText = layerMapp.layerName
            confCoucheNode.Attributes().Append(coucheAttribute)

            Dim tableAttribute As XmlAttribute = XmlDoc.CreateAttribute("table")
            tableAttribute.InnerText = layerMapp.layerTable
            confCoucheNode.Attributes().Append(tableAttribute)

            Dim formAttribute As XmlAttribute = XmlDoc.CreateAttribute("formulaire")
            formAttribute.InnerText = layerMapp.layerForm
            confCoucheNode.Attributes().Append(formAttribute)

            LayersNode.AppendChild(confCoucheNode)
        Next

        root.AppendChild(LayersNode)
        XmlDoc.AppendChild(root)
        XmlDoc.Save(xmlPath)

    End Sub

    Private Sub saveWorkspace()
        saveLayers()
        saveXML()
    End Sub
    Private Sub menuSaveDoc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles menuSaveDoc.Click
        saveWorkspace()
    End Sub

    Private Sub addGroupLayerBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles addGroupLayerBtn.Click
        Dim groupLayer As GroupLayer = New GroupLayer()
        groupLayer.Name = "Nouveau groupe"
        m_mapControl.AddLayer(groupLayer)
    End Sub
    Private Function GetColor(ByVal r As Integer, ByVal g As Integer, ByVal b As Integer) As IRgbColor
        Dim pColor As IRgbColor = New RgbColor()
        pColor.Red = r
        pColor.Green = g
        pColor.Blue = b
        Return pColor
    End Function
    Public Sub showForms()
        If selectedLayer Is Nothing OrElse String.IsNullOrWhiteSpace(selectedLayer.Name) Then
            Exit Sub
        End If
        MainTab.SelectedIndex = 1
        'Dim panelGeometry As SplitterPanel = LayerFormContainer.Panel1
        'Dim panelFormLayer As SplitterPanel = LayerFormContainer.Panel2
        'If Not layersMap.ContainsKey(selectedLayer.Name) Then
        '    panelFormLayer.Controls.Clear()
        '    panelGeometry.Controls().Clear()
        '    Return
        'End If
        'Dim layerMapp As LayerMapping = layersMap.Item(selectedLayer.Name)
        If configLayers Is Nothing OrElse configLayers.Count <= 0 Then
            Return
        End If
        Dim layerTable As String = String.Empty
        Dim layerForm As String = String.Empty
        For Each confLayer As LayersSiteConfig In configLayers
            If selectedLayer.Name = confLayer.layerLabel Then
                layerTable = confLayer.layerTable
                layerForm = confLayer.layerForm
                Exit For
            End If
        Next
        If layerTable Is Nothing OrElse String.IsNullOrWhiteSpace(layerTable) Then
            Exit Sub
        End If
        GeometryFormContainer.Controls.Clear()
        Dim geometryForm As UserControl = New UserControl()
        'If layerWhereDraw IsNot Nothing And TypeOf layerWhereDraw Is IFeatureLayer Then
        Dim featureLayer As IFeatureLayer = selectedLayer
        If featureLayer.FeatureClass IsNot Nothing Then
            Dim esriType As esriFeatureType = featureLayer.FeatureClass.ShapeType

            Select Case esriType
                Case esriGeometryType.esriGeometryPoint
                    geometryForm = New PointForm()
                Case esriGeometryType.esriGeometryPolyline
                    geometryForm = New LineForm()
                Case esriGeometryType.esriGeometryPolygon
                    geometryForm = New PolygoneForm()
            End Select
        End If
        ' End If
        geometryForm.Show()
        GeometryFormContainer.Controls.Add(geometryForm)
        Dim setWorkSpaceMethod As Reflection.MethodInfo = geometryForm.GetType().GetMethod("setWorkspace")
        If setWorkSpaceMethod IsNot Nothing Then
            Dim params(setWorkSpaceMethod.GetParameters().Length - 1) As Object
            params(0) = Me
            setWorkSpaceMethod.Invoke(geometryForm, params)
        End If

        FormTab.Controls.Clear()
        Dim typeLayer As Type = Type.GetType("SILMConfig." & layerForm)
        'Dim typeTemp As Type = Layer1.GetType() f
        Dim formLayer As Form = Activator.CreateInstance(typeLayer, dbConnexion) ' New Layer1()
        formLayer.TopLevel = False
        formLayer.Text = selectedLayer.Name
        Dim layerNamePropInfo As System.Reflection.PropertyInfo = formLayer.GetType().GetProperty("layerName")
        If layerNamePropInfo IsNot Nothing Then
            layerNamePropInfo.SetValue(formLayer, layerTable, Nothing)
        End If
        ' formLayer.layerName = selectedLayer.Name
        formLayer.Show()
        formLayer.ControlBox = False
        'formLayer.Width = panelFormLayer.Width
        formLayer.FormBorderStyle = Windows.Forms.FormBorderStyle.FixedDialog
        AddHandler formLayer.Move, AddressOf dragFormEvent
        formLayer.MaximizeBox = False
        formLayer.MinimizeBox = False
        'formLayer.Height = panelFormLayer.Height
        Dim workspacePropInfo As System.Reflection.PropertyInfo = formLayer.GetType().GetProperty("workspace")
        If workspacePropInfo IsNot Nothing Then
            workspacePropInfo.SetValue(formLayer, Me, Nothing)
        End If
        FormTab.Controls.Add(formLayer)
        'LayerFormContainer.Panel1Collapsed = True
    End Sub


    Public Sub activateDrawing()
        'If layerWhereDraw IsNot Nothing Then
        If selectedLayer IsNot Nothing Then
            cancelDrawing()
            layerWhereDraw = selectedLayer
            AddHandler axMapControl1.OnMouseDown, AddressOf drawGeometryOnMap
            mapGeomContainer.Panel1Collapsed = False
            MainTab.SelectedIndex = 0
        End If

        'End If
    End Sub

    Public Sub cancelDrawing()
        If lastGeometry IsNot Nothing Then
            Dim pGraCont As IGraphicsContainer = m_mapControl.ActiveView
            pGraCont.DeleteElement(lastGeometry)
            lastGeometry = Nothing
            m_mapControl.ActiveView.Refresh()
            'layerWhereDraw.Panel1Collapsed = True
            'layerWhereDraw = Nothing
        End If

        RemoveHandler axMapControl1.OnMouseDown, AddressOf drawGeometryOnMap
    End Sub

    Public Function validateDrawing() As String
        If lastGeometry IsNot Nothing Then
            Dim pGraCont As IGraphicsContainer = m_mapControl.ActiveView
            pGraCont.DeleteElement(lastGeometry)
            Dim geometry As IGeometry = lastGeometry.Geometry
            Dim featureLayer As IFeatureLayer = layerWhereDraw
            Dim feature As IFeature = featureLayer.FeatureClass.CreateFeature()

            feature.Shape = geometry
            feature.Store()
            showGeometryProperties(geometry)
            m_mapControl.ActiveView.Refresh()
            lastGeometry = Nothing
            layerWhereDraw = Nothing
            mapGeomContainer.Panel1Collapsed = True

            Dim pQFilt As IQueryFilter = New QueryFilter()
            pQFilt.WhereClause = " FID = " & feature.OID
            Dim updateCursor As IFeatureCursor = featureLayer.FeatureClass.Update(pQFilt, True)
            Dim pF As IFeature = updateCursor.NextFeature
            If pF IsNot Nothing Then
                Dim fieldIndex As Integer = featureLayer.FeatureClass.FindField(SILMProperties.SIG_COL_NAME)
                pF.Value(fieldIndex) = featureLayer.Name & "_" & feature.OID
                updateCursor.UpdateFeature(pF)
            End If
            Return featureLayer.Name & "_" & feature.OID
        End If
        Return Nothing
    End Function

    Private Sub addGeometry()
        'If layerWhereDraw IsNot Nothing Then
        '    MsgBox("Vous avez déja démarrer une localisation, veuillez la terminer d'abord !!")
        '    'Return
        'End If
        If selectedLayer IsNot Nothing Then
            ' layerWhereDraw = selectedLayer
            'showForms()
            'AddHandler axMapControl1.OnMouseDown, AddressOf drawGeometryOnMap
        End If
    End Sub


    Private Sub AxTOCControl1_OnMouseDown(ByVal sender As System.Object, ByVal e As ESRI.ArcGIS.Controls.ITOCControlEvents_OnMouseDownEvent) Handles AxTOCControl1.OnMouseDown
        cancelDrawing()
        'Exit if not right mouse button
        If e.button = 1 Then
            getSelectedlayerData(e.x, e.y)


        ElseIf e.button = 2 Then
            updateSymbologies(e.x, e.y)
        End If

    End Sub

    Public Function getSelectedlayerData(ByVal x As Integer, ByVal y As Integer)
        Dim map As IMap = New Map
        Dim layer As ILayer = New FeatureLayer
        Dim other As Object = New Object
        Dim index As Object = New Object
        Dim item As esriTOCControlItem
        'Determine what kind of item has been clicked on
        AxTOCControl1.HitTest(x, y, item, map, layer, other, index)

        If layer Is Nothing Then
            selectedLayer = Nothing
            Return selectedLayer
            Exit Function
        End If

        If selectedLayer Is layer And selectedLayer IsNot Nothing Then
            Return selectedLayer
        End If

        selectedLayer = layer
        If Not TypeOf layer Is IFeatureLayer Then
            'layerCols.Items.Clear()
            Return Nothing
            Exit Function
        End If
        addGeometry()
        Return selectedLayer
    End Function

    Public Sub updateSymbologies(ByVal x As Integer, ByVal y As Integer)
        Dim map As IMap = New Map
        Dim layer As ILayer = New FeatureLayer
        Dim other As Object = New Object
        Dim index As Object = New Object
        Dim item As esriTOCControlItem

        'Determine what kind of item has been clicked on
        AxTOCControl1.HitTest(x, y, item, map, layer, other, index)

        If layer Is Nothing Then Exit Sub
        If Not TypeOf layer Is IFeatureLayer Then Exit Sub

        'QI to IFeatureLayer and IGeoFeatuerLayer interface
        Dim featureLayer As IFeatureLayer = layer
        Dim geoFeatureLayer As IGeoFeatureLayer = featureLayer
        Dim simpleRenderer As ISimpleRenderer = geoFeatureLayer.Renderer

        'Create the form with the SymbologyControl
        Dim symbolForm As New frmSymbol

        'Get the IStyleGalleryItem
        Dim styleGalleryItem As IStyleGalleryItem = Nothing
        'Select SymbologyStyleClass based upon feature type
        Select Case featureLayer.FeatureClass.ShapeType
            Case esriGeometryType.esriGeometryPoint
                styleGalleryItem = symbolForm.GetItem(esriSymbologyStyleClass.esriStyleClassMarkerSymbols, simpleRenderer.Symbol)
            Case esriGeometryType.esriGeometryPolyline
                styleGalleryItem = symbolForm.GetItem(esriSymbologyStyleClass.esriStyleClassLineSymbols, simpleRenderer.Symbol)
            Case esriGeometryType.esriGeometryPolygon
                styleGalleryItem = symbolForm.GetItem(esriSymbologyStyleClass.esriStyleClassFillSymbols, simpleRenderer.Symbol)
        End Select

        'Release the form
        symbolForm.Dispose()
        Me.Activate()
        If styleGalleryItem Is Nothing Then Exit Sub

        'Create a new renderer
        simpleRenderer = New SimpleRenderer
        'Set its symbol from the styleGalleryItem
        simpleRenderer.Symbol = styleGalleryItem.Item
        'Set the renderer into the geoFeatureLayer
        geoFeatureLayer.Renderer = simpleRenderer

        'Fire contents changed event that the TOCControl listens to
        m_mapControl.ActiveView.ContentsChanged()
        'Refresh the display
        m_mapControl.Refresh(esriViewDrawPhase.esriViewGeography, Nothing, Nothing)
    End Sub




    Private Sub ToolStripButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton1.Click
        If selectedLayer IsNot Nothing And selectedLayer IsNot Nothing Then
            m_mapControl.Map.DeleteLayer(selectedLayer)
            selectedLayer = Nothing
        End If
    End Sub

    Private Sub Workspace_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
        Dim result As MsgBoxResult = MsgBox("Enregistrer l'espace du travail " & workspaceName & " ?", MsgBoxStyle.YesNoCancel, "Enregistrer les modifications")
        removed = True
        If MsgBoxResult.Yes = result Then
            saveWorkspace()
        ElseIf result = MsgBoxResult.Cancel Then
            e.Cancel = True
            removed = False
        End If
    End Sub



    'Private Sub applyScale_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '    If selectedLayer Is Nothing Or Not TypeOf selectedLayer Is IFeatureLayer Then
    '        Exit Sub
    '    End If
    '    Dim featureLayer As IFeatureLayer = selectedLayer
    '    If allScale.Checked Then

    '    Else
    '        If cboxMaxScale.SelectedItem Is Nothing Or cboxMinScale.SelectedItem Is Nothing Then
    '            'featureLayer.
    '            MsgBox("Veuillez selectionner des valeurs correctes !!")
    '            Exit Sub
    '        Else
    '            featureLayer.MinimumScale = cboxMinScale.SelectedItem.ToString().Split(":"c)(1)
    '            featureLayer.MaximumScale = cboxMaxScale.SelectedItem.ToString().Split(":"c)(1)
    '        End If
    '    End If
    'End Sub

    Private Sub PerformClick(ByVal command As String)
        ' If MapOrPageLayout = GisControls.MAP Then
        '    Me.graphicBar.CommandPool.get_Command(Me.graphicBar.Find(command)).OnClick()
        'Else
        '    Me.graphicBar.CommandPool.get_Command(Me.graphicBar.Find(command)).OnClick()
        'End If
    End Sub

    Private Sub drawPolyLine()

        Dim pLine As IPolyline
        Dim pGraCont As IGraphicsContainer
        Dim pRubberLine As IRubberBand
        Dim pElem As IElement


        ' QI for the IGraphicsContainerSelect interface on the document's activeview
        pGraCont = m_mapControl.ActiveView

        ' Create a new RubberLine
        pRubberLine = New RubberLine

        'Check which mouse button was pressed...

        ' Return a new Line from the tracker object using TrackNew
        pLine = pRubberLine.TrackNew(m_mapControl.ActiveView.ScreenDisplay, Nothing)

        If Not pLine Is Nothing Then
            ' Create a new LineElement and set its Geometry
            pElem = New LineElement
            pElem.Geometry = pLine
            lastGeometry = pElem
            'Add the new element at Z order zero
            pGraCont.AddElement(pElem, 0)
        End If

        ' Refresh the activeview
        m_mapControl.ActiveView.Refresh()
        RemoveHandler axMapControl1.OnMouseDown, AddressOf drawGeometryOnMap
    End Sub
    Private Sub drawPoint()
        'Dim pMXDoc As IMxDocument
        Dim pPoint As IPoint
        Dim pGraCont As IGraphicsContainer

        Dim pRubberPoint As IRubberBand
        Dim pElem As IElement = Nothing

        ' QI for the IGraphicsContainerSelect interface on the document's activeview
        pGraCont = m_mapControl.ActiveView

        ' Create a new RubberPolygon
        pRubberPoint = New RubberPoint

        ' Return a new Polygon from the tracker object using TrackNew
        pPoint = pRubberPoint.TrackNew(m_mapControl.ActiveView.ScreenDisplay, Nothing)

        If Not pPoint Is Nothing Then
            ' Create a new PolygonElement and set its Geometry
            pElem = New MarkerElement
            pElem.Geometry = pPoint
            lastGeometry = pElem
            'Add the new element at Z order zero
            pGraCont.AddElement(pElem, 0)
        End If

        ' Refresh the activeview
        m_mapControl.ActiveView.Refresh()
        RemoveHandler axMapControl1.OnMouseDown, AddressOf drawGeometryOnMap
    End Sub

    Private Sub drawPolygon()
        'Dim pMXDoc As IMxDocument
        Dim pPoly As IPolygon
        Dim pGraCont As IGraphicsContainer

        Dim pRubberPoly As IRubberBand
        Dim pElem As IElement = Nothing

        ' QI for the IGraphicsContainerSelect interface on the document's activeview
        pGraCont = m_mapControl.ActiveView

        ' Create a new RubberPolygon
        pRubberPoly = New RubberPolygon

        'Check which mouse button was pressed...

        ' If button = 1 Then ' If button 1 (left) then create a new polygon (TrackNew)

        ' Return a new Polygon from the tracker object using TrackNew
        pPoly = pRubberPoly.TrackNew(m_mapControl.ActiveView.ScreenDisplay, Nothing)

        If Not pPoly Is Nothing Then
            ' Create a new PolygonElement and set its Geometry
            pElem = New PolygonElement
            pElem.Geometry = pPoly
            lastGeometry = pElem

            'Add the new element at Z order zero
            pGraCont.AddElement(pElem, 0)
        End If

        ' Refresh the activeview
        m_mapControl.ActiveView.Refresh()
        RemoveHandler axMapControl1.OnMouseDown, AddressOf drawGeometryOnMap
    End Sub

    Private Sub drawGeometryOnMap(ByVal sender As System.Object, ByVal e As ESRI.ArcGIS.Controls.IMapControlEvents2_OnMouseDownEvent)
        If layerWhereDraw IsNot Nothing And TypeOf layerWhereDraw Is IFeatureLayer Then
            Dim featureLayer As IFeatureLayer = layerWhereDraw
            If featureLayer.FeatureClass IsNot Nothing Then
                Dim esriType As esriFeatureType = featureLayer.FeatureClass.ShapeType

                Select Case esriType
                    Case esriGeometryType.esriGeometryPoint
                        drawPoint()
                    Case esriGeometryType.esriGeometryPolyline
                        drawPolyLine()
                    Case esriGeometryType.esriGeometryPolygon
                        drawPolygon()
                End Select
            End If

        End If
    End Sub


    Private Sub dragFormEvent(ByVal sender As Object, ByVal e As EventArgs)
        If sender IsNot Nothing And TryCast(sender, Form) IsNot Nothing Then
            TryCast(sender, Form).Location = New System.Drawing.Point(0, 0)
        End If
    End Sub

    Private Sub showGeometryProperties(ByVal geometry As IGeometry)
        If GeometryFormContainer.Controls.Count <= 0 Then
            Return
        End If
        Dim ctrl As Control = GeometryFormContainer.Controls.Item(0)
        If ctrl IsNot Nothing Then
            Dim methodInfo As Reflection.MethodInfo = ctrl.GetType().GetMethod("setGeometry")
            If methodInfo IsNot Nothing Then
                Dim params(methodInfo.GetParameters().Length - 1) As Object
                params(0) = geometry
                methodInfo.Invoke(ctrl, params)
            End If
        End If
    End Sub

    Public Sub setCoordonne(ByVal lat As Double, ByVal lon As Double)
        If lastGeometry IsNot Nothing And TryCast(lastGeometry, MarkerElement) IsNot Nothing Then

            Dim pGraCont As IGraphicsContainer = m_mapControl.ActiveView
            pGraCont.DeleteElement(lastGeometry)

            Dim pElem As IElement = Nothing
            pGraCont = m_mapControl.ActiveView

            Dim point As IPoint = New Point()
            point.PutCoords(lat, lon)
            pElem = New MarkerElement
            pElem.Geometry = point
            lastGeometry = pElem
            pGraCont.AddElement(pElem, 0)
            m_mapControl.ActiveView.Refresh()
        End If
    End Sub

    Private Sub axMapControl1_OnMouseUp(ByVal sender As System.Object, ByVal e As ESRI.ArcGIS.Controls.IMapControlEvents2_OnMouseUpEvent) Handles axMapControl1.OnMouseUp
        If lastGeometry IsNot Nothing Then
            showGeometryProperties(lastGeometry.Geometry)
        End If
    End Sub

    'Public Function getLayerByTable(ByVal tableName As String) As String
    '    For Each layerData As String In layersMap.Keys()
    '        Dim layerMapp As LayerMapping = layersMap.Item(layerData)
    '        If layerMapp.layerTable = tableName Then
    '            Return layerMapp.layerName
    '        End If
    '    Next
    '    Return Nothing
    'End Function

    Private Function getFeatureByLayerName(ByVal layerName As String)
        For i = 0 To m_mapControl.LayerCount
            Dim layer As ILayer = m_mapControl.Layer(i)
            If layer.Name = layerName Then
                Return layer
            End If
        Next
        Return Nothing
    End Function

    Public Sub deleteNodes(ByVal tableName As String, ByVal nodes As List(Of String))
        If selectedLayer Is Nothing Then
            Return
        End If
        Dim layerName As String = selectedLayer.Name ' getLayerByTable(tableName)
        If layerName Is Nothing Or nodes Is Nothing Or nodes.Count <= 0 Then
            Return
        End If

        Dim featureLayer As IFeatureLayer = getFeatureByLayerName(layerName)
        If featureLayer Is Nothing Then
            Return
        End If
        Dim pQFilt As IQueryFilter = New QueryFilter()
        pQFilt.WhereClause = ""
        For Each node As String In nodes
            If pQFilt.WhereClause <> "" Then
                pQFilt.WhereClause = pQFilt.WhereClause & " or "
            End If
            pQFilt.WhereClause = pQFilt.WhereClause & " " & SILMProperties.SIG_COL_NAME & " = '" & node & "' "
        Next
        Dim cursor As IFeatureCursor = featureLayer.FeatureClass.Update(pQFilt, False)
        Try
            Dim pf As IFeature = cursor.NextFeature()
            While pf IsNot Nothing
                cursor.DeleteFeature()
                pf = cursor.NextFeature
            End While
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
        m_mapControl.ActiveView.Refresh()
    End Sub

    Public Sub highlightNodes(ByVal tableName As String, ByVal nodes As List(Of String))
        If selectedLayer Is Nothing Then
            Return
        End If
        Dim layerName As String = selectedLayer.Name  'getLayerByTable(tableName)
        If layerName Is Nothing Or nodes Is Nothing Or nodes.Count <= 0 Then
            Return
        End If

        Dim featureLayer As IFeatureLayer = getFeatureByLayerName(layerName)
        If featureLayer Is Nothing Then
            Return
        End If
        Dim pQFilt As IQueryFilter = New QueryFilter()
        pQFilt.WhereClause = ""
        For Each node As String In nodes
            If pQFilt.WhereClause <> "" Then
                pQFilt.WhereClause = pQFilt.WhereClause & " or "
            End If
            pQFilt.WhereClause = pQFilt.WhereClause & " " & SILMProperties.SIG_COL_NAME & " = '" & node & "' "
        Next
        Dim featureSelection As IFeatureSelection = featureLayer
        m_mapControl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeoSelection, featureLayer, Nothing)
        featureSelection.SelectFeatures(pQFilt, esriSelectionResultEnum.esriSelectionResultNew, False)
    End Sub





    'Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    '    If selectedLayer Is Nothing Then
    '        Return
    '    End If
    '    Dim layerConf As LayerMapping = layersMap.Item(selectedLayer.Name)
    '    If layerConf Is Nothing Then
    '        Return
    '    End If

    '    If isColExistInTable(SILMProperties.SIG_COL_NAME, selectedLayer.Name, dbConnexion) Then
    '        Return
    '    End If
    '    Dim con As SqlConnection = New SqlConnection(dbConnexion)
    '    Try
    '        con.Open()
    '        ' For Each layerName As String In layersMap.Keys()

    '        Dim query As String = "ALTER TABLE " & _
    '        layerConf.layerTable & _
    '        " ADD " & _
    '        SILMProperties.SIG_COL_NAME & " " & _
    '        "VARCHAR(20) DEFAULT null"
    '        Dim cmd As SqlCommand = New SqlCommand(query, con)
    '        cmd.ExecuteNonQuery()

    '        con.Close()
    '    Catch ex As Exception

    '    End Try
    '    Dim featureLayer As IFeatureLayer = getFeatureByLayerName(selectedLayer.Name)
    '    If featureLayer Is Nothing Then
    '        Return
    '    End If
    '    AddFieldToFeatureClass(featureLayer.FeatureClass, createField(SILMProperties.SIG_COL_NAME, "Identifiant GIS", esriFieldType.esriFieldTypeString))
    'End Sub

    Private Sub OrographieToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OrographieToolStripMenuItem.Click
        Dim intOrg As New OrHyGraSit
        intOrg.databaseName = dbConnexion
        intOrg.Show()
    End Sub

    Private Sub GéologiegéomorphologieToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GéologiegéomorphologieToolStripMenuItem.Click
        Dim intGeolGeol As New GeolGeomSit
        intGeolGeol.databaseName = dbConnexion
        intGeolGeol.Show()
    End Sub

    Private Sub ClimatToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ClimatToolStripMenuItem.Click
        Dim intClim As New ClimSite
        intClim.databaseName = dbConnexion
        intClim.Show()
    End Sub

    Private Sub HydrogéologieToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles HydrogéologieToolStripMenuItem.Click
        Dim inthydG As New HydroGeoSit
        inthydG.databaseName = dbConnexion
        inthydG.Show()
    End Sub

    Private Sub HydrologieToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles HydrologieToolStripMenuItem.Click
        Dim inthyd As New HydrSit
        inthyd.databaseName = dbConnexion
        inthyd.Show()
    End Sub

    Private Sub SédimentologieToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SédimentologieToolStripMenuItem.Click
        Dim intSedim As New SedimSite
        intSedim.databaseName = dbConnexion
        intSedim.Show()
    End Sub

    Private Sub StationsMétéorologiquesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles StationsMétéorologiquesToolStripMenuItem.Click
        Dim intStatMet As New StatMeteo
        intStatMet.databaseName = dbConnexion
        intStatMet.Show()
    End Sub

    Private Sub InfrastructureToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles InfrastructureToolStripMenuItem.Click
        Dim intEquip As New Equipement
        intEquip.databaseName = dbConnexion
        intEquip.Show()
    End Sub

    Private Sub RéseauHydrographiqueToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub FloreFauneToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FloreFauneToolStripMenuItem.Click
        Dim intFloreSys As New FloFauNouv(dbConnexion)
        intFloreSys.databaseName = dbConnexion
        intFloreSys.Show()
    End Sub

    Private Sub HabitatsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles HabitatsToolStripMenuItem.Click
        Dim intHab As New HabitatsGlob
        intHab.databaseName = dbConnexion
        intHab.Show()
    End Sub

    Private Sub VégétationToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles VégétationToolStripMenuItem.Click
        Dim intVeg As New VegetationNouv
        intVeg.databaseName = dbConnexion
        intVeg.Show()
    End Sub


    Private Sub VégétationToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles VégétationToolStripMenuItem1.Click
        Dim intVegPatr As New VegPatrim
        intVegPatr.databaseName = dbConnexion
        intVegPatr.Show()
    End Sub

    Private Sub LocalitésToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LocalitésToolStripMenuItem.Click
        Dim intLocl As New LocaliteSite
        intLocl.databaseName = dbConnexion
        intLocl.Show()
    End Sub

    Private Sub PopulationActiveToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PopulationActiveToolStripMenuItem.Click
        Dim intPop As New SuiviPopSit
        intPop.databaseName = dbConnexion
        intPop.Show()
    End Sub

    Private Sub NiveauDInstructionToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NiveauDInstructionToolStripMenuItem.Click
        Dim intNivInst As New StructInstr
        intNivInst.databaseName = dbConnexion
        intNivInst.Show()
    End Sub

    Private Sub ActivitésHumainesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ActivitésHumainesToolStripMenuItem.Click
        Dim intActHum As New ActivitHumSit
        intActHum.databaseName = dbConnexion
        intActHum.Show()
    End Sub


    Private Sub BénéficesDusageToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BénéficesDusageToolStripMenuItem.Click
        Dim intBenf As New ActBenefice
        intBenf.databaseName = dbConnexion
        intBenf.Show()
    End Sub

    Private Sub StatutsFonciersDeLespaceToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles StatutsFonciersDeLespaceToolStripMenuItem.Click
        Dim intSitFanc As New SiteStFoncier
        intSitFanc.databaseName = dbConnexion
        intSitFanc.Show()
    End Sub


    Private Sub DysfonctionnementsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DysfonctionnementsToolStripMenuItem.Click
        Dim intDysf As New DysfonSite
        intDysf.databaseName = dbConnexion
        intDysf.Show()
    End Sub

    Private Sub PlanDeGestionToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PlanDeGestionToolStripMenuItem.Click
        Dim intPAG As New PlanAmGest
        intPAG.databaseName = dbConnexion
        intPAG.Show()
    End Sub

    Private Sub RéglementationToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RéglementationToolStripMenuItem.Click
        Dim intReg As New RglementNouv
        intReg.databaseName = dbConnexion
        intReg.Show()
    End Sub

    Private Sub ActeursconcernésToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ActeursconcernésToolStripMenuItem.Click
        Dim typX As New TypologieNivX
        typX.databaseName = dbConnexion
        typX.Text = "Concernés"
        typX.Table1 = "ConcernCateg"
        typX.Table2 = "ConcernTyp"
        typX.Show()
    End Sub

    Private Sub EtudesComplémentairesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EtudesComplémentairesToolStripMenuItem.Click
        Dim intEtudComp As New EtudCompl
        intEtudComp.databaseName = dbConnexion
        intEtudComp.Show()
    End Sub

    Private Sub ZonageToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ZonageToolStripMenuItem.Click
        Dim intZong As New ZonageSit
        intZong.databaseName = dbConnexion
        intZong.Show()
    End Sub

    Private Sub EtudesDiagnostiquesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EtudesDiagnostiquesToolStripMenuItem.Click
        Dim intDiagS As New DiagSite
        intDiagS.databaseName = dbConnexion
        intDiagS.Show()
    End Sub

    Private Sub showFormBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles showFormBtn.Click
        If selectedLayer IsNot Nothing Then
            showForms()
        End If
    End Sub

    Private Sub layerConfigBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        activateDrawing()
    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        cancelDrawing()
        mapGeomContainer.Panel1Collapsed = True
    End Sub

    Private Sub btnConfirm_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConfirm.Click
        oidValue.Text = validateDrawing()
        If oidParentText IsNot Nothing Then
            oidParentText.Text = oidValue.Text
        End If
        mapGeomContainer.Panel1Collapsed = True
    End Sub

    
    Private Sub OutilsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OutilsToolStripMenuItem.Click
        If toolsContainer.Height = 25 Then
            toolsContainer.Height = 88
            OutilsToolStripMenuItem.Text = "- Outils"
        Else
            toolsContainer.Height = 25
            OutilsToolStripMenuItem.Text = "+ Outils"
        End If
    End Sub
End Class